<template>
	<div class="add-content">
		<list-title :data="header"></list-title>
		<el-form :model="contentForm" :rules="rules" ref="contentForm" label-width="150px">
			<el-form-item label="标题" prop="data.title" style="width: 830px;">
				<el-input v-model="contentForm.data.title" placeholder="标题" style="width: 640px"></el-input>
				<el-color-picker v-model="contentForm.data.titlecolor"></el-color-picker>
			</el-form-item>
			<el-form-item label="所属栏目(可多选)" prop="parentid">
				<el-select v-model="contentForm.parentid" filterable placeholder="请选择栏目" @change="chooseCategory">
					<el-option label="顶级栏目" value="0"></el-option>
					<el-option v-for="(item, index) in categoryList" 
					:key="index" 
					:label="item.name" 
					:value="item.catid"
					:disabled="checkCatidsRepeat(item.catid)">
					</el-option>
				</el-select>
				<ul class="category" v-if="contentForm.data.catids.length > 0">
					<li v-for="(item, index) in contentForm.data.catids" :key="index">
						<span>{{ item.name }}</span>
						<i @click="removeCategory(index)">×</i>
					</li>
				</ul>
			</el-form-item>
			<el-form-item label="预览图" prop="data.preview" style="width: 600px;">
				<upload-oss 
				:stsdomain="this.$domain.ac" 
				:ossdomain="this.$ossdomain" 
				:limit="6" 
				:fileList="contentForm.data.preview" 
				:maxSize="20" 
				@insertFile="insertFile"
				@delFile="delFile">
				</upload-oss>
			</el-form-item>
			<el-form-item label="是否置顶" prop="data.istop">
				<el-switch v-model="contentForm.data.istop"></el-switch>
			</el-form-item>
			<el-form-item label="标签" style="width: 680px;">
				<el-input type="text" placeholder="请输入标签" v-model='newTags' maxlength="16" show-word-limit style="width: 275px;"></el-input>
				<el-button type="primary" @click="createTag()">添加</el-button>
				<el-button @click="getHotTags()" :disabled='tagsLibLock'>
					常用标签选择  <span class="el-icon-loading" v-if='tagsLibLock'></span>
				</el-button>
				<p class="help">多个标签请用英文逗号（,）分开</p>
				<ul class="tag" v-if='contentForm.tags.length > 0'>
					<li v-for="(item, index) in contentForm.tags" :key="index">
						<span>{{ item.tag_name }}</span>
						<i @click="removeTag(index)">×</i>
					</li>
				</ul>
				<ul class="tag-lib" v-if='tagsLib.length > 0'>
					<li v-for="(item, index) in tagsLib" :key="index">
						<span @click="addTag(item)">{{ item.tag_name }}</span>
					</li>
				</ul>
			</el-form-item>
			<el-form-item label="视频" prop="data.video" style="width: 800px;">
				<upload-oss
				:stsdomain="$domain.ac" 
				:ossdomain="$ossdomain" 
				:field="'file'" 
				:fileList="[]" 
				:type="'mp4'" 
				:limit="1" 
				:fileSrc="contentForm.data.video" 
				:maxSize="100" 
				@insertFile="insertVideo"
				@delFile="delVideo">
					</upload-oss>
			</el-form-item>
			<el-form-item label="是否外链" prop="data.outside">
				<el-switch v-model="contentForm.data.outside"></el-switch>
			</el-form-item>
			<el-form-item label="打开方式" v-if="contentForm.data.outside" prop="data.url_target" style="width: 600px;">
				<el-select v-model="contentForm.data.url_target" placeholder="请选择打开方式">
					<el-option label="self" :value="'1'"></el-option>
					<el-option label="blank" :value="'2'"></el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="外链地址" v-if="contentForm.data.outside" prop="data.outside_url" style="width: 600px;">
				<el-input v-model="contentForm.data.outside_url" placeholder="外链地址"></el-input>
			</el-form-item>
			<el-form-item label="来源" prop="data.source" style="width: 830px;">
				<el-input v-model="contentForm.data.source" placeholder="来源"></el-input>
			</el-form-item>
			<el-form-item label="作者" prop="data.author" style="width: 830px;">
				<el-input v-model="contentForm.data.author" placeholder="作者"></el-input>
			</el-form-item>
			<el-form-item label="关键词" prop="data.keyword" style="width: 830px;">
				<el-input v-model="contentForm.data.keyword" placeholder="关键词"></el-input>
			</el-form-item>
			<el-form-item label="描述" prop="data.describe" style="width: 830px;">
				<el-input type="textarea" :rows="3" placeholder="请输入描述" v-model="contentForm.data.describe"></el-input>
			</el-form-item>
			<el-form-item label="内容" prop="data.content" v-show="!contentForm.data.outside">
				<ueditor-oss :domain="this.$domain.cms" 
				:value="contentForm.data.content" 
				:config="ueditor.config" 
				:id="'0'" 
				@getUeditorLength="getUeditorLength"
				ref="ue">
				</ueditor-oss>
			</el-form-item>
			<el-form-item label="添加时间" prop="data.add_time" style="width: 350px;">
				<el-date-picker
				v-model="contentForm.data.add_time"
				format="yyyy-MM-dd HH:mm:ss"
				value-format="yyyy-MM-dd HH:mm:ss"
				type="datetime"
				placeholder="选择日期时间">
				</el-date-picker>
				<p class="help">为空的话，系统将自动选择当前时间</p>
			</el-form-item>
			<el-form-item label="是否显示" prop="data.display">
				<el-switch v-model="contentForm.data.display"></el-switch>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" plain @click="submitForm('contentForm', '23')" :disabled='contentForm.submitLock'>
					保存 <span class="el-icon-loading" v-if='contentForm.submitLock'></span>
				</el-button>
				<el-button @click="resetForm('contentForm')" v-if='contentForm.data.id==0'>重 置</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
import ListTitle from "pc/common/Title"
import UploadOss from "pc/common/UploadOss"
import FileUpload from "pc/common/FileUpload"
import UeditorOss from "pc/common/UeditorOss"
import {changeToBool, changeUploadFormatBack} from "static/js/common.js"

export default {
	inject: ['reload'],
	data() {
		return {
			/*栏目ID*/
			catid: this.$route.query.catid,
			/*头部数据*/
			header: {
				title: '添加内容',
				reload: false,
				buttons: [
					{
						title: '内容列表',
						type: 'primary',
						pathName: 'pc/epi/content/ContentList',
						query: {
							catid: this.$route.query.catid,
							flag: this.$route.query.flag,
						},
					}
				]
			},
			newTags: '',
			tagsLib: [
				// {
				// 	tid: '1',
				// 	tag_name: 'HTML',
				// 	heat: 0
				// },
				// {
				// 	tid: '2',
				// 	tag_name: 'CSS',
				// 	heat: 0
				// }, 
				// {
				// 	tid: '3',
				// 	tag_name: 'YII',
				// 	heat: 0
				// }
			],
			tagsLibLock: false,//获取标签库的锁
			categoryList: [],//所有栏目，便于选择
			contentForm: {
				submitLock: false,
				parentid: '',//选择的栏目ID
				data: {
					id: 0,
					catids: [
						// {
						// 	'catid': 1,
						// 	'name': '国内新闻',
						// }
					],
					title: '',
					titlecolor: null,
					flag: [],
					preview: [],
					video: '',
					istop: false,
					outside: false,
					url_target: '2',
					outside_url: '',
					source: '',
					author: '',
					keyword: '',
					describe: '',
					content: '',
					state: 1,
					rejected_reason: '',
					display: true,
					add_time: '',
				},
				tags: [],
				catids: "",//主要是为了获取修改数据的时候，能够放到 contentForm.data.catids 的默认值中
				modifyData: false,//判断修改数据是否成功获取，true说明获取成功,防止监听重复操作
				modifyData2: false//判断修改数据是否成功获取，true说明获取成功,防止监听重复操作
			},
			rules: {
				data: {
					catids: [
						{ required: true, message: '请选择栏目', trigger: 'change' }
					],
					title: [
						{ required: true, message: '请输入标题', trigger: 'blur' },
						{ min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur' }
					]
				},
			},
			ueditor: {
				config: {}
			},
			
		};
	},
	components: {
		ListTitle,
		FileUpload,
		UploadOss,
		UeditorOss
	},
	created: function() {

		/*取出分类列表*/
		this.getContentCategoryList()
		/*判断是否是单页，如果单页，去掉 标题栏的列表按钮*/
		if(this.$route.query.flag == 1){
			this.header.title = '编辑内容'
			// this.header.buttons = [] 注释原因：单页的话，也需要 列表 按钮，就当是 返回 作用
		}
		if(this.$route.query.flag == 1 && this.$route.query.id == undefined){
			/*请求旧数据*/
			this.getContent()
		}
		/*如果是修改，取出旧数据*/
		if(this.$route.query.id){
			this.getContent(this.$route.query.id)
		}
	},
	methods: {
		/*获取栏目*/
		getContentCategoryList: function(){
			if(this.$api.contentCategoryList != undefined){
				this.$get(this.$api.contentCategoryList).then(res => {
					// console.log(res);
					if(res.data.code === 0){
						if(res.data.data != undefined){
							this.categoryList = []
							Object.keys(res.data.data).forEach((k) => {
								let indent = '';
								for(var i=1; i<res.data.data[k].level; i++){
									if(i == 1){
										indent += '|---';
									}else{
										indent += '---';
									}
								}
								this.categoryList.push ({
									catid: res.data.data[k].catid,
									name: indent + res.data.data[k].name
								});
								/*添加默认的分类，此分类不能删*/
								if(this.$route.query.catid == res.data.data[k].catid){
									this.contentForm.data.catids.push(
										{
											'catid': res.data.data[k].catid,
											'name': res.data.data[k].name,
										}
									)
								}
							})
						}
						this.tableLoading = false
					}
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*选择栏目*/
		chooseCategory: function(val){
			/*遍历categoryList，找出选择的字段*/
			let obj = this.categoryList.find((item)=>{
				return item.catid === val;
			});
			let getName = obj.name;
			getName = getName.replace(/^\|\-+/,"");

			/*contentForm.data.catids里排重，不重复的就添加*/
			let has = false
			this.contentForm.data.catids.forEach((item, index) => {
				if(item.catid == val){
					has = true
				}
			})

			if(!has){
				this.contentForm.data.catids.push(
					{
						'catid': val,
						'name': getName,
					}
				)
			}
			this.contentForm.parentid = ''//选择内容清除，便于再次选择
		},
		/*删除栏目*/
		removeCategory(index) {
			if(this.contentForm.data.catids[index].catid == this.$route.query.catid){//如果是默认分类，不能删
				this.$message({
					showClose: true,
					message: '默认分类，不能删除',
					type: 'error'
				});
			}else{
				this.contentForm.data.catids.splice(index, 1);
			}
		},
		/*
		提交添加、修改表单
		*/
		submitForm(formName, flag) {
			if(!this.contentForm.submitLock){
				this.$refs[formName].validate((valid) => {
					if (valid) {
						this.contentForm.data.content = this.$refs.ue.getUEContent()//子组件中获取content
						// console.log(this.contentForm.data.content)

						this.contentForm.data.state = 3

						this.contentForm.submitLock = true;
						/*添加、修改分类*/
						let apiUrl = this.$api.addContent//默认是添加
						if(this.contentForm.data.id > 0){//修改
							apiUrl = this.$api.modifyContent
						}
						// let data = this.contentForm.data
						let data = JSON.parse(JSON.stringify(this.contentForm.data))

						if(data.content != undefined){
							data.content = data.content.replace(new RegExp(this.$domain.ac, 'g'),"")//把内容中图片的全局路径改成相对路径（去掉域名）
						}
						if(data.content != undefined && data.preview.length == 0){
							data.preview = null
						}
						// console.log(data, 'aaaa')
						// return

						/*添加、修改内容*/
						if(apiUrl != undefined){
							this.$post(apiUrl, {
								Content: data,
								Tags: this.contentForm.tags,
							}).then(res => {
								// console.log(res);
								/*成功*/
								if(res.data.code == 0){
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'success'
									});
									if(this.contentForm.data.id > 0 || this.$route.query.flag == 1){//当是添加 或 单页 的时候
										this.$router.go(-1)	
									}else{
										this.$refs[formName].resetFields();
										this.getContentCategoryList();
										this.contentForm.tags = []
										this.contentForm.data.flag = []
										this.contentForm.data.catids = []
										this.$refs.ue.setUEContentEmpty()//清空ueditor内容
									}
								}else{
									this.$message({
										showClose: true,
										message: res.data.info,
										type: 'error'
									});
								}
								this.contentForm.submitLock = false;
							});
						}
					} else {
						console.log('error submit!!');
						return false;
					}
				});
			}
		},
		/*重置表单*/
		resetForm(formName) {
			this.$refs[formName].resetFields();
			this.$refs.ue.setUEContentEmpty()//清空ueditor内容
		},
		/*产生新标签*/
		createTag() {
			if(this.newTags != ''){
				let tmp = this.newTags.split(',')
				tmp.forEach((item, index)=>{
					if(item != ''){
						let newTag = {
										tid: '',
										tag_name: item,
										heat: 0
									}
						if(!this.__hasTag(newTag)){
							this.contentForm.tags.push(newTag)
						}
					}
				})
				this.newTags = ''
			}
		},
		/*删除标签*/
		removeTag(index) {
			// console.log(index)
			this.contentForm.tags.splice(index, 1);
		},
		/*加载热度高的标签*/
		getHotTags() {
			this.tagsLibLock = true
			this.$get(this.$api.tagsList, {
				hot: 50
			}).then(res => {
				if(res.data.code == 0){
					// console.log(res.data.data.list)
					this.tagsLib = []
					Object.keys(res.data.data.list).forEach((k) => {
						this.tagsLib.push(
							{
								tid: res.data.data.list[k].tid,
								tag_name: res.data.data.list[k].tag_name,
								heat: res.data.data.list[k].heat,
							}
						)
					})
					this.tagsLibLock = false
				}else{
					this.$message({
						showClose: true,
						message: res.data.info,
						type: 'error'
					});
				}
				this.contentForm.submitLock = false;
			})
			.catch(err => {})
			.finally(() => {}) 
		},
		/*库中选择并添加标签*/
		addTag(tag) {
			if(!this.__hasTag(tag)){
				this.contentForm.tags.push(tag)
			}
		},
		/*判断 已添加的标签中，是否包含此标签*/
		__hasTag(tag) {
			let has = false
			this.contentForm.tags.forEach((item, index)=>{
				if((item.tid == tag.tid && item.tid != '') || item.tag_name == tag.tag_name){
					has = true
				}
			})
			return has
		},
		/*插入上传的图片*/
		// insertPic(list, field){
		// 	for(let i=0; i<list.length; i++){
		// 		this.contentForm.data[field].push(
		// 			{
		// 				name: '',
		// 				url:  list[i].url
		// 			}
		// 		)
		// 	}
		// },
		/*删除上传的图片*/
		// delPic(index, field){
		// 	this.contentForm.data[field].splice(index, 1)
		// },
		/*插入上传的文件*/
		insertFile(file, field){
			// console.log(file instanceof Array)
			if(file instanceof Array){//如果是数组的话，说明是图片
				for(let i=0; i<file.length; i++){
					this.contentForm.data.preview.push(
						{
							name: '',
							url:  file[i].url
						}
					)
				}
			}else{//单个文件路径

			}
		},
		/*删除上传的文件*/
		delFile(index){
			if(index >= 0){//图片
				this.contentForm.data.preview.splice(index, 1)
			}else{//文件路径

			}
		},
		/*上传视频*/
		insertVideo(fileSrc, field){
			// console.log(field);
			this.contentForm.data.video = fileSrc
		},
		/*删除视频*/
		delVideo(field){
			this.contentForm.data.video = ''
		},
		/*取出需要修改的数据*/
		getContent: function(){
			if(this.$api.modifyContent != undefined){	
				this.header.title = '编辑内容'
				/*取出需要修改的数据*/
				this.contentForm.submitLock = true;
				this.$get(this.$api.modifyContent, {
					'id': this.$route.query.id,
					'catid': this.$route.query.catid
				}).then(res => {
					if(res.data.code == 0){
						if(res.data.data.content){
							// console.log(res.data.data.content.content)
							this.contentForm.data.id = res.data.data.content.content_id
							// catids: [
							// 	// {
							// 	// 	'catid': 1,
							// 	// 	'name': '国内新闻',
							// 	// }
							// ],
							this.contentForm.data.title = res.data.data.content.title
							this.contentForm.data.titlecolor = res.data.data.content.titlecolor
							this.contentForm.data.flag = (res.data.data.content.flag != undefined)?res.data.data.content.flag:[]
							this.contentForm.data.preview = changeUploadFormatBack(res.data.data.content.preview)
							this.contentForm.data.video = res.data.data.content.video
							this.contentForm.data.istop = changeToBool(res.data.data.content.istop)
							this.contentForm.data.outside = changeToBool(res.data.data.content.outside)
							this.contentForm.data.url_target = res.data.data.content.url_target
							this.contentForm.data.outside_url = res.data.data.content.outside_url
							this.contentForm.data.source = res.data.data.content.source
							this.contentForm.data.author = res.data.data.content.author
							this.contentForm.data.keyword = res.data.data.content.keyword
							this.contentForm.data.describe = res.data.data.content.describe
							// this.contentForm.data.content = res.data.data.content.content
							this.contentForm.data.content = res.data.data.content.content.replace(/img src=\"\/uploads/g, 'img src="' + this.$domain.cms + '/uploads')
							this.contentForm.data.state = res.data.data.content.state
							this.contentForm.data.display = changeToBool(res.data.data.content.display)
							this.contentForm.data.add_time = res.data.data.content.add_time

							this.contentForm.catids = res.data.data.content.catids

							Object.keys(res.data.data.tags).forEach((k) => {
								this.contentForm.tags.push (
									{
										tid: res.data.data.tags[k].tag.tid,
										tag_name: res.data.data.tags[k].tag.tag_name,
										heat: res.data.data.tags[k].tag.heat
									}
								)
							})
						}

					}else{
						this.$message({
							showClose: true,
							message: res.data.info,
							type: 'error'
						});
					}
					this.contentForm.submitLock = false;
				})
				.catch(err => {})
				.finally(() => {}) 
			}
		},
		/*编辑器调用，返回统计的字数*/
		getUeditorLength: function(len, id){
			if(id == 0){//判断是否是内容编辑器
				
			}
		},
	},
	watch: {
		/*监听categoryList, contentForm连个参数，为了把老的所属分类放上去*/
		modifyCategoryData: {
			handler: function(val) {
				// console.log(val.categoryList, 'fff')
				if(!this.modifyData2 && val.categoryList != '' && val.contentForm.catids != ''){
					this.modifyData2 = true
					// console.log(val.contentForm.catids, 'dd')
					let tmpArr = val.contentForm.catids.split(',')
					// console.log(tmpArr)
					this.contentForm.data.catids = []

					Object.keys(tmpArr).forEach((k) => {
						Object.keys(val.categoryList).forEach((k1) => {
							if(val.categoryList[k1].catid == tmpArr[k]){
								// console.log(val.categoryList[k1].catid)
								this.contentForm.data.catids.push(
									{
										'catid': val.categoryList[k1].catid,
										'name': val.categoryList[k1].name.replace(/^\|\-+/,""),
									}
								)
							}
						})
					})
				}
			},
			deep: true
		}
	},
    computed: {
    	/*验证 所属分类 是否已经选择了，不能再选*/
		checkCatidsRepeat(val) {
			return function (val) {
				let has = false
				this.contentForm.data.catids.find((item) => {
					if(val == item.catid){
						has = true
					}
				})
				return (has)
			}
		},
		/*监听categoryList, contentForm连个参数，为了把老的所属分类放上去*/
		modifyCategoryData() {
			const {categoryList, contentForm} = this
			return {
				categoryList,
				contentForm
			}
		}
    }
};
</script>

<style lang="stylus" scoped>
.add-content
	form
		margin-top: 10px
		.el-color-picker
			margin-left: 10px
			position: absolute
		.category,.tag
			// border: red 1px solid
			padding-top: 10px
			width: 453px
			overflow: hidden
			li
				float: left
				border: #d6d6d6 1px solid
				margin-right: 10px
				margin-bottom: 10px
				cursor: pointer
				position: relative
				span
					display: block
					padding: 0 10px
					height: 100%
					font-size: 12px
		 	li:hover i
				display: block
			li
				i
					width: 18px
					height: 18px
					line-height: 18px
					font-style: normal
					text-align: center
					color: #fff
					position: absolute
					display: inline-block
					border-radius: 100%
					background-color: rgba(0, 0, 0, .5)
					top: -9px
					right: -9px
					display: none
			li
				i:hover
					background-color: rgba(0, 0, 0, 1)
		.tag-lib
			border: #4abadb 1px solid
			padding: 0 10px
			overflow: hidden
			li
				float: left
				cursor: pointer
				padding: 0px
				// border: red 1px solid
				margin-right: 10px
				span
					font-size: 12px
			li:hover
				color: #4abadb
	/*Ueditor行高有问题*/
	/deep/ .edui-default .edui-toolbar .edui-combox .edui-combox-body
			line-height: 20px !important
	/deep/ .edui-default .edui-button-body
			line-height: 20px !important
	/deep/ .edui-splitbutton-body
			line-height: 20px !important
	/deep/ .edui-menubutton-body
			line-height: 20px !important
	/*Ueditor 下拉箭头偏右*/
	/deep/ .edui-default .edui-toolbar .edui-combox-body .edui-arrow
			background-position: -742px 0px
</style>